package tsql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import common.ErrCode;

public class sqlTest {
    String driverName = "com.mysql.cj.jdbc.Driver";

    // 用户连接信息
    String url = "jdbc:mysql://localhost:3306/game1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true";// 连接数据库的URL
    String user = "root";
    String passwd = "123456";

    public void done() {
        try {
            System.out.println("------------------------- mysql 测试 start ------------------------");

            // 启动驱动
            Class.forName(driverName);

            // 连接成功后，第一步获得connection（代表数据库）
            Connection cn = DriverManager.getConnection(url, user, passwd);

            // 第二步再获得能够执行sql对象的statement
            Statement sm = cn.createStatement();

            // statement，可以开始执行SQL的对象了
            ResultSet rst = sm.executeQuery("select * from d_users where id < 11111");

            System.out.println("query datas:");
            // result.next()返回的是boolean型
            while (rst.next()) {
                // 调用方法，给其方法传入字段名 来显示刚才查询到的内容
                // System.out.printf("---------\n", rst.getInt("id"));
                ErrCode.info("---------%d, %s", rst.getInt("id"), rst.getString("name"));
            }

            // 关闭资源
            cn.close();
            sm.close();
            rst.close();

        } catch (SQLException e) {
            // System.err.printf("mysql opr err:%s\n", e.getMessage());
            e.printStackTrace();

        } catch (Exception e) {
            // System.err.printf("mysql other err:%s\n", e.getMessage());
            ErrCode.error("mysql other err:%s", e.getMessage());
            e.printStackTrace();
        }

        System.out.println("-------------------------- mysql 测试 end ----------------------------");

    }

    /*
     * public void done2() {
     * String url = "jdbc:mysql://localhost:3306/game1";
     * String username = "root";
     * String password = "123456"; // 替换为您在安装MySQL时设置的密码
     * try {
     * Connection connection = DriverManager.getConnection(url, username, password);
     * Statement statement = connection.createStatement();
     * ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable;");
     * while (resultSet.next()) {
     * System.out.println("ID: " + resultSet.getInt("id") + ", Name: " +
     * resultSet.getString("name"));
     * }
     * } catch (SQLException e) {
     * e.printStackTrace();
     * }
     * }
     */
}
